package com.ly.aidlpratice.messenger

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.ly.aidlpratice.R
import com.ly.aidlpratice.util.logDebug
import com.ly.aidlpratice.util.logError
import java.lang.Exception
import java.lang.ref.WeakReference

class MessengerActivity : AppCompatActivity() {

    private val mTag: String by lazy { this::class.java.simpleName }

    private lateinit var mServiceConnect: ServiceConnection

    private lateinit var mServiceMessenger: Messenger

    internal lateinit var textView: TextView

    private var mIsConnect = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_messenger)

        mServiceConnect = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                logDebug(mTag, "onServiceConnected[$name]")
                service?.also {
                    mServiceMessenger = Messenger(it)
                    mIsConnect = true

                    logDebug(mTag, "send client handler to service")
                    val msg = Message.obtain()
                    //将客户端的Messenger发送给服务端，服务端就可以向客户端发送消息了
                    msg.replyTo = Messenger(ClientHandler(this@MessengerActivity))
                    msg.what = MessengerService.MessengerHandler.MSG_WHAT_GET_CLIENT_HANDLER
                    mServiceMessenger.send(msg)
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                logDebug(mTag, "onServiceDisconnected[$name]")
                mIsConnect = false
            }

        }

        textView = findViewById(R.id.textView2)
        findViewById<Button>(R.id.button5).setOnClickListener {
            if (mIsConnect) {
                logDebug(mTag, "send msg to service")
                val msg = Message.obtain()
                msg.what = MessengerService.MessengerHandler.MSG_WHAT_FROM_CLIENT_CLICK
                mServiceMessenger.send(msg)
            } else {
                Toast.makeText(this, "未绑定服务", Toast.LENGTH_SHORT).show()
            }
        }

        findViewById<Button>(R.id.button6).setOnClickListener {
            bindService(
                Intent(this, MessengerService::class.java),
                mServiceConnect,
                Service.BIND_AUTO_CREATE
            )

//            val intent = Intent("com.ly.aidlpratice.action.MESSENGER1")
//            intent.setPackage("com.ly.aidlpratice")
//            bindService(
//                intent,
//                mServiceConnect,
//                Service.BIND_AUTO_CREATE
//            )
        }

        findViewById<Button>(R.id.button7).setOnClickListener {
            try {
                unbindService(mServiceConnect)
                mIsConnect = false
            } catch (e: Exception) {
                logError(mTag, e)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mIsConnect = false
    }

    internal class ClientHandler(activity: MessengerActivity) : Handler(Looper.getMainLooper()) {

        private val mTag: String by lazy { this::class.java.simpleName }

        private var mActivity: WeakReference<MessengerActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            mActivity.get()?.also {
                when (msg.what) {
                    MSG_WHAT_FROM_SERVICE -> {
                        logDebug(mTag, "收到服务端发来的消息")
                        @SuppressLint("SetTextI18n")
                        it.textView.text = "随机数字：${msg.arg1}"
                    }
                }
            }
        }

        companion object {
            const val MSG_WHAT_FROM_SERVICE = 0
        }
    }
}